package com.bawan.vims.common.util;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p> Description	: NetworkUtil.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: JOCHEN ZHENG </p>
 * <p> Create		: 2015年3月25日 上午9:58:32 </p> 
 * <p> version 		: 1.0 </p>
 */
public class NetworkUtil {
	private static final Logger logger = LoggerFactory.getLogger(NetworkUtil.class);
	
	/**
	 * 访问IP请求超时时间
	 */
	static final int REACH_TIMEOUT = 5000;
	
	/**
	 * 获得http请求的客户端IP地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;

	}
	
	/**
	 * 判断某个IP是否可通
	 * @param ip
	 * @return
	 */
	public static boolean canReachable(String ip) {
		try {
			InetAddress address = InetAddress.getByName(ip);

			if (address.isReachable(REACH_TIMEOUT)) {
				logger.debug("[NetworkUtil] [PING] IP Address[" + ip + "] success...");
				return true;
			} else {
				logger.debug("[NetworkUtil] [PING] IP Address[" + ip + "] failed...");
				return false;
			}
		} catch (Exception e) {
			logger.debug("[NetworkUtil] [PING] IP Address[" + ip + "] exception: " + e, e);
			return false;
		}
	}
}
